package marcelvm;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * Knihovna pro praci se souborem
 * @author honzee
 */
public class IOLibrary {

    private static Map<String, Scanner> rFiles
            = new HashMap<String, Scanner>();
    private static Map<String, PrintWriter> wFiles
            = new HashMap<String, PrintWriter>();

    /**
     * Otevre soubor pro cteni
     */
    public static void openFileForRead(String fileName)
            throws MarcelVMException, IOException {
        if (wFiles.containsKey(fileName)) {
            throw new MarcelVMException("Error while opening file for read - " +
                    "this file is opened for write");
        }

        rFiles.put(fileName, new Scanner(new FileReader(fileName)));
    }

    /**
     * Otevre soubor pro zapis
     */
    public static void openFileForWrite(String fileName)
            throws MarcelVMException, IOException {
        if (rFiles.containsKey(fileName) || wFiles.containsKey(fileName)) {
            throw new MarcelVMException("Error while opening file for write - " +
                    "this file is already opened for read or write");
        }

        wFiles.put(fileName, new PrintWriter(new FileWriter(fileName)));
    }

    /**
     * Zavre soubor
     */
    public static void closeFile(String fileName)
            throws MarcelVMException {
        if (rFiles.containsKey(fileName)) {
            Scanner reader = rFiles.remove(fileName);
            reader.close();
        } else if (wFiles.containsKey(fileName)) {
            PrintWriter writer = wFiles.remove(fileName);
            writer.close();
        } else {
            throw new MarcelVMException("Error while closing file for read - " +
                    "no such file for read opened");
        }
    }

    /**
     * Precte dalsi integer ze souboru
     */
    public static Integer readInt(String fileName)
            throws MarcelVMException, IOException {
        if (!rFiles.containsKey(fileName)) {
            throw new MarcelVMException("Error while reading from file - " +
                    "no such file for read opened");
        }
        Scanner reader = rFiles.get(fileName);
        if (!reader.hasNextInt()) {
            throw new MarcelVMException("Error while reading from file - " +
                    "next value cannot be interpreted as integer");
        }

        return reader.nextInt();
    }

    /**
     * Zapise retezec do souboru
     */
    public static void write(String value, String fileName)
            throws MarcelVMException, IOException {
        if (!wFiles.containsKey(fileName)) {
            throw new MarcelVMException("Error while writing to a file - " +
                    "no such file for write opened");
        }
        PrintWriter writer = wFiles.get(fileName);

        writer.print(value);
    }

}
